import 'dart:io';

import 'package:excel/excel.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:study_demo/base/BaseController.dart';
import 'package:trina_grid/trina_grid.dart';

import '../../../util/file.dart';
import '../../../util/utils.dart';

class ReadExcelController extends BaseController {
  List outPuts = <OutPut>[];

  final columns = <TrinaColumn>[].obs;

  final rows = <TrinaRow>[].obs;

  late TrinaGridStateManager stateManager;

  Widget currencyRenderer(TrinaColumnRendererContext ctx) {
    Color color = Colors.white;

    var value = ctx.cell.value.toString();

    return Container(
        color: value.isEmpty ? Color(0xFFF2F2F2) : Colors.blue,
        // padding: EdgeInsets.symmetric(vertical: 12, horizontal: 15),
        margin: EdgeInsets.symmetric(horizontal: 1),
        alignment: Alignment.center,
        height: 40,
        child: Text(
          ctx.column.type.applyFormat(ctx.cell.value),
          style: TextStyle(color: color, fontSize: 14),
          textAlign: TextAlign.center,
        ));
  }

  Widget defaultRenderer(TrinaColumnRendererContext ctx) {
    Color color = Color(0xFF33CCCC);

    if (ctx.column.field == 'day_cost') {
      if (ctx.cell.value == 119) {
        color = Color(0xFF666699);
      }
    }

    if (ctx.cell.value == '0') {
      ctx.cell.value = '';
    }

    return Container(
        color: Color(0xFFF2F2F2),
        padding: EdgeInsets.symmetric(vertical: 12, horizontal: 15),
        child: Text(
          ctx.column.type.applyFormat(ctx.cell.value.toString()),
          style: TextStyle(color: color),
          textAlign: TextAlign.center, // 单元格中文字的位置
        ));
  }

  Widget finishRateRenderer(TrinaColumnRendererContext ctx) {
    Color color = Color(0xFF666699);

    return Container(
        color: Color(0xFFF2F2F2),
        padding: EdgeInsets.symmetric(vertical: 12, horizontal: 15),
        child: Text(
          ctx.column.type.applyFormat(ctx.cell.value.toString()),
          style: TextStyle(color: color),
          textAlign: TextAlign.center, // 单元格中文字的位置
        ));
  }

  Widget footRenderer(TrinaColumnFooterRendererContext ctx) {
    return Container(
      color: Colors.white,
    );
  }

  Widget titleRenderer(TrinaColumnTitleRendererContext ctx) {
    Color bgColor = Colors.blue;

    if (ctx.column.field == 'id1' || ctx.column.field == 'id2') {
      bgColor = Colors.white;
    }

    return Container(
        alignment: Alignment.center,
        margin: EdgeInsets.all(1),
        decoration: BoxDecoration(
          color: bgColor,
        ),
        child: Text(
          ctx.column.type.applyFormat(ctx.column.title),
          style: TextStyle(color: Colors.white),
          textAlign: TextAlign.center, // 单元格中文字的位置
        ));
  }

  @override
  void onInit() {
    super.onInit();
  }

  addColumns() {
    // print('addColumns');
    var columns = <TrinaColumn>[];
    columns.assignAll([
      _trinaColumn(
        title: '',
        field: 'id1',
        width: 135,
        minWidth: 135,
        renderer: currencyRenderer,
        type: TrinaColumnType.text(),
      ),
      _trinaColumn(
        title: '月计划',
        field: 'month_plan1',
        type: TrinaColumnType.text(),
      ),
      _trinaColumn(
        title: '日完成',
        field: 'day_finish',
        type: TrinaColumnType.text(),
      ),
      _trinaColumn(
        title: '月累计',
        field: 'month_total1',
        type: TrinaColumnType.text(),
      ),
      _trinaColumn(
        title: '完成率',
        field: 'finish_rate1',
        width: 100,
        minWidth: 100,
        renderer: finishRateRenderer,
        type: TrinaColumnType.text(),
      ),
      _trinaColumn(
        title: '',
        field: 'id2',
        width: 120,
        minWidth: 120,
        renderer: currencyRenderer,
        type: TrinaColumnType.text(),
      ),
      _trinaColumn(
        title: '月计划',
        field: 'month_plan2',
        type: TrinaColumnType.text(),
      ),
      _trinaColumn(
        title: '日进厂',
        field: 'day_enter_factory',
        type: TrinaColumnType.text(),
      ),
      _trinaColumn(
        title: '月累计',
        field: 'month_total2',
        type: TrinaColumnType.text(),
      ),
      _trinaColumn(
        title: '完成率',
        field: 'finish_rate2',
        type: TrinaColumnType.text(),
      ),
      _trinaColumn(
        title: '日耗',
        field: 'day_cost',
        type: TrinaColumnType.text(),
      ),
      _trinaColumn(
        title: '月耗',
        field: 'month_cost',
        type: TrinaColumnType.text(),
      ),
      _trinaColumn(
        title: '库存',
        field: 'inventory',
        type: TrinaColumnType.text(),
      ),
    ]);
    stateManager.insertColumns(stateManager.bodyColumns.length, columns);
  }

  _trinaColumn(
      {String title = '',
      String field = '',
      TrinaColumnType? type,
      double width = 80,
      TrinaColumnRenderer? renderer,
      double minWidth = 80}) {
    return TrinaColumn(
      title: title,
      field: field,
      titleRenderer: titleRenderer,
      // footerRenderer: footRenderer,
      type: type!,
      enableSorting: false,
      enableColumnDrag: false,
      enableTitleChecked: false,
      enableFilterMenuItem: false,
      enableSetColumnsMenuItem: false,
      enableHideColumnMenuItem: true,
      enableDropToResize: false,
      enableContextMenu: false,
      // 显示或隐藏菜单按钮
      renderer: renderer ?? defaultRenderer,
      width: width,
      // cellPadding: EdgeInsets.symmetric(vertical: 0, horizontal: 0),
      // titlePadding: EdgeInsets.all(0),
      titleTextAlign: TrinaColumnTextAlign.center,
      // 表头文字在单元格中的位置
      // 单元格的宽度
      minWidth: minWidth, // 单元格的最小宽度
    );
  }

  void onReady() {
    super.onReady();
  }

  List? result;

  readExcel() async {
    result = await pickExcel();
    result?.removeLast();
    print('result:$result');
    if (result != null) {
      refreshData();
    }
  }

  refreshData() {
    clear();
    addColumns();
    outPuts.clear();
    for (var row in result!.sublist(2)) {
      var data1 = getData(row, 1);
      var data3 = getData(row, 3);

      var finishRate = '';
      if (data1 != null) {
        var data = data3 * 100 / data1;
        finishRate = formatPercentage(data);
        ;
      }
      var outPut = OutPut(
        getData(row, 0),
        data1,
        getData(row, 2),
        data3,
        finishRate.toString(),
        getData(row, 5),
        getData(row, 6),
        getData(row, 7),
        getData(row, 8),
        getData(row, 9),
        getData(row, 10),
        getData(row, 11),
        getData(row, 12),
      );
      outPuts.add(outPut);
    }
    rows.clear();
    for (int i = 0; i < outPuts.length; i++) {
      var outPut = outPuts[i];
      rows.add(
        TrinaRow(
          cells: {
            'id1': TrinaCell(value: outPut.id1.replaceAll('m3', 'm\u00B3')),
            'month_plan1': TrinaCell(value: outPut.monthPlan1),
            'day_finish': TrinaCell(value: outPut.dayFinish),
            'month_total1': TrinaCell(value: outPut.monthTotal1),
            'finish_rate1': TrinaCell(value: outPut.finishRate1),
            'id2': TrinaCell(value: outPut.id2.replaceAll('m3', 'm\u00B3')),
            'month_plan2': TrinaCell(value: outPut.monthPlan2),
            'day_enter_factory': TrinaCell(value: outPut.dayEnterFactory),
            'month_total2': TrinaCell(value: outPut.monthTotal2),
            'finish_rate2': TrinaCell(value: outPut.finishRate2),
            'day_cost': TrinaCell(value: outPut.dayCost),
            'month_cost': TrinaCell(value: outPut.monthCost),
            'inventory': TrinaCell(value: outPut.inventory),
          },
        ),
      );
    }

    TrinaGridStateManager.initializeRowsAsync(
      columns,
      rows,
    ).then((value) {
      stateManager.refRows.assignAll(value);
      stateManager.setShowLoading(false);
    });
  }

  clear() {
    stateManager.removeColumns(columns);
    stateManager.removeAllRows();
  }

  export() async {
    try {
      // 创建 Excel 文件
      var excel = Excel.createExcel();
      var sheet = excel['Sheet1'];

      List<CellValue> cells = [];
      columns.forEach((it) {
        var value = TextCellValue(it.title);
        cells.add(value);
      });
      // 添加表头
      sheet.appendRow(cells);

      rows.forEach((row) {
        cells.clear();
        row.cells.forEach((key, value) {
          if (key == 'id1' || key == 'id2' || key == 'finish_rate1') {
            cells.add(TextCellValue(value.value));
          } else {
            cells.add(IntCellValue(value.value));
          }
        });
        // 添加数据行
        sheet.appendRow(cells);
      });

      // 保存文件
      final fileBytes = excel.save();

      // 让用户选择保存位置
      final String? outputFile = await FilePicker.platform.saveFile(
        fileName: formatDate(DateTime.now()) + '.xlsx',
        type: FileType.custom,
        allowedExtensions: ['xlsx'],
      );

      if (outputFile != null) {
        final file = File(outputFile);
        await file.writeAsBytes(fileBytes!);
      }
    } catch (e) {
      debugPrint('导出Excel出错: $e');
    }
  }

  dynamic getData(List<Data?>? row, int index) {
    // print('row: $row');
    // print('index: $index');
    // print('row[index]: ${row[index]}');
    // print('row[index]!.value: ${row[index]!.value}');

    if (row == null || row[index] == null) {
      return null;
    }
    CellValue? value = row[index]!.value;
    // print('color:${row[index]!.cellStyle!.fontColor}');
    switch (value) {
      case TextCellValue():
        // print('text: ${value.value}');
        var text = value.value.text ?? '';
        if (text.isEmpty) {
          if (value.value.children!.isNotEmpty) {
            var list = value.value.children;
            for (var item in list!) {
              if (item.text!.isNotEmpty) {
                text += item.text!;
              }
            }
          }
        }
        return text;
      case IntCellValue():
        return value.value;
      case DoubleCellValue():
        // print('double: ${value.value}');
        return value.value;
      case FormulaCellValue():
        return value.formula;
      default:
        return '';
    }
  }

  String formatPercentage(double data) {
    final isWholeNumber = data == data.truncateToDouble();

    if (isWholeNumber) {
      return '${data.toStringAsFixed(1)}%'; // 强制保留 .0（如 300.0%）
    } else {
      // 非整数，保留2位小数（如 109.52%）
      var formatted = data.toStringAsFixed(2);

      // 移除末尾多余的0（如106.90 → 106.9）
      formatted = formatted.replaceAll(RegExp(r'0+$'), '');

      // 确保不会留下单独的小数点（如106. → 106）
      formatted = formatted.replaceAll(RegExp(r'\.$'), '');

      return '$formatted%';
    }
  }
}

class OutPut {
  final String? id1;
  final int? monthPlan1;
  final int? dayFinish;
  final int? monthTotal1;
  final String? finishRate1;
  final String? id2;
  final int? monthPlan2;
  final int? dayEnterFactory;
  final int? monthTotal2;
  final int? finishRate2;
  final int? dayCost;
  final int? monthCost;
  final int? inventory;

  OutPut(
    this.id1,
    this.monthPlan1,
    this.dayFinish,
    this.monthTotal1,
    this.finishRate1,
    this.id2,
    this.monthPlan2,
    this.dayEnterFactory,
    this.monthTotal2,
    this.finishRate2,
    this.dayCost,
    this.monthCost,
    this.inventory,
  );
}
